#include "ApplicationLayer.h"
#include "ProtocolFactory.h"


CApplicationLayer::CApplicationLayer(void)
{
	name = "APPLICATION";
}

CApplicationLayer::~CApplicationLayer(void)
{
	layers.clear();
}

void CApplicationLayer::addProtocol( const boost::shared_ptr<IProtocol>& protocol )
{
	add(protocol);
}

const boost::shared_ptr<IProtocol>& CApplicationLayer::getProtocol( const std::string& name ) const
{
	citerator it = std::find_if(cbegin(), cend(), ProtocolComparer(name));

	if(it == cend()) 
	{
		throw new std::exception();
	}

	return (*it).second;
}

void CApplicationLayer::removeProtocol( const std::string& name )
{
	getContainerToModify().erase(name);
}

StackUtils::e_Status CApplicationLayer::Decode( CPacket& packet )
{
	std::for_each(rbegin(), rend(), ProtocolDecode(packet));
	return StackUtils::E_SUCCESS;
}

StackUtils::e_Status CApplicationLayer::Encode( CPacket& packet )
{
	std::for_each(begin(), end(), ProtocolEncode(packet));
	return StackUtils::E_SUCCESS;
}

void CApplicationLayer::add( const boost::shared_ptr<IProtocol>& element )
{
	getContainerToModify().insert(std::pair<std::string, boost::shared_ptr<IProtocol> >(element->getName(), element));
}

void CApplicationLayer::init()
{
	boost::shared_ptr<IProtocol> DNS_ptr(CProtocolFactory::CreateProtocol("DNS"));
	add(DNS_ptr);

	boost::shared_ptr<IProtocol> FTP_ptr(CProtocolFactory::CreateProtocol("FTP"));
	add(FTP_ptr);

	boost::shared_ptr<IProtocol> HTTP_ptr(CProtocolFactory::CreateProtocol("HTTP"));
	add(HTTP_ptr);
}
